package com.neuresys.database.implstorage.gwtmobileimpl;

import com.google.code.gwt.database.client.Database;
import com.google.code.gwt.database.client.SQLError;
import com.google.code.gwt.database.client.SQLResultSet;
import com.google.code.gwt.database.client.SQLResultSetRowList;
import com.google.code.gwt.database.client.SQLTransaction;
import com.google.code.gwt.database.client.StatementCallback;
import com.google.code.gwt.database.client.TransactionCallback;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.typedarrays.client.JsUtils;
import com.google.gwt.typedarrays.client.Uint8ArrayNative;
import com.google.gwt.user.server.Base64Utils;
import com.neuresys.database.databaseapi.Connection;
import com.neuresys.database.databaseapi.DatabaseOpenEvent;
import com.neuresys.database.databaseapi.DatabaseOpenHandler;
import com.neuresys.database.databaseapi.DatabaseSaveEvent;
import com.neuresys.database.databaseapi.DatabaseSaveHandler;
import com.neuresys.database.databaseapi.StoreDataService;
import com.neuresys.database.databaseimpl.jssqlite.Base64Coder;
import com.neuresys.database.databaseimpl.jssqlite.SQLite;
import com.neuresys.database.databaseimpl.jssqlite.SQLiteDatabaseOpenEvent;
import com.neuresys.database.databaseimpl.jssqlite.SQLiteDatabase;

public class WebDatabaseStoreDataService implements StoreDataService  {

	private Database db;
	private static final String databaseName="MyDatabase";
	private static final String databaseVersion="1.0";
	private static final String databaseDecription="MyDatabase description";
	
	/* (non-Javadoc)
	 * @see com.neuresys.database.implstorage.gwtmobileimpl.StoreDataService#dropAllDatabase()
	 */
	@Override
	public void dropAllDatabase()
	{Database db = Database.openDatabase(databaseName, databaseVersion, databaseDecription, 50000);
	db.transaction(new TransactionCallback() {

		@Override
		public void onTransactionStart(SQLTransaction tx) {
			tx.executeSql("DROP TABLE MyDatabaseSQLite ",null);
			
		}

		@Override
		public void onTransactionSuccess() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTransactionFailure(SQLError error) {
			// TODO Auto-generated method stub
			
		}
	});
	}
	/* (non-Javadoc)
	 * @see com.neuresys.database.implstorage.gwtmobileimpl.StoreDataService#dropDatabase(java.lang.String)
	 */
	@Override
	public void dropDatabase(final String name)
	{
		Database db = Database.openDatabase(databaseName, databaseVersion, databaseDecription, 50000);
		db.transaction(new TransactionCallback() {
		    public void onTransactionStart(SQLTransaction tx) {
		    	  tx.executeSql("CREATE TABLE IF NOT EXISTS MyDatabaseSQLite ("
			                + "id INT8 NOT NULL PRIMARY KEY ,"
			                + "name VARCHAR, value BLOB)",null);
			        tx.executeSql("drop from  MyDatabaseSQLite where id=?",new Object []{name.hashCode()});
		    }

			@Override
			public void onTransactionSuccess() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTransactionFailure(SQLError error) {
				// TODO Auto-generated method stub
				
			}});
		    
		
			        		//	 tx.executeSql("DROP TABLE MyDatabaseSQLite ",null);
		
	}
	/* (non-Javadoc)
	 * @see com.neuresys.database.implstorage.gwtmobileimpl.StoreDataService#getDatabase(java.lang.String, com.neuresys.database.databaseapi.DatabaseOpenHandler)
	 */
	@Override
	public  void getDatabase(final String name,final DatabaseOpenHandler handler)
	{
		Database db = Database.openDatabase(databaseName, databaseVersion, databaseDecription, 50000);
		db.transaction(new TransactionCallback() {
		    public void onTransactionStart(SQLTransaction tx) {
		    	  tx.executeSql("CREATE TABLE IF NOT EXISTS MyDatabaseSQLite ("
		                + "id INT8 NOT NULL PRIMARY KEY ,"
		                + "name VARCHAR, value BLOB)",null);
		    	  GWT.log("select value from  MyDatabaseSQLite where id="+name.hashCode());
		        tx.executeSql("select value from  MyDatabaseSQLite where id=?",new Object []{name.hashCode()},
		        		new StatementCallback<JavaScriptObject>(){

					@Override
					public void onSuccess(SQLTransaction transaction,
							SQLResultSet<JavaScriptObject> resultSet) {
							
						 for (JavaScriptObject row : resultSet.getRows()) { 
							 GWT.log(new JSONObject(row).toString());
							 //String name=row
							 Uint8ArrayNative read = Uint8ArrayNative.create(JsUtils.arrayBufferFromString(Base64Coder.decodeString((new JSONObject(row).get("value").isString().stringValue()))));
							 GWT.log("Database read"+read);
								
						 handler.onSucceed(new SQLiteDatabaseOpenEvent(read));
								 }
						 if (resultSet.getRows().getLength()==0) handler.onSucceed(new SQLiteDatabaseOpenEvent());
						
					}

					@Override
					public boolean onFailure(SQLTransaction transaction,
							SQLError error) {
						GWT.log(error.getMessage()+"");
						// TODO Auto-generated method stub
						return false;
					}

					
        	
        });
	}

			@Override
			public void onTransactionSuccess() {
				GWT.log("success");	
			}

			@Override
			public void onTransactionFailure(SQLError error) {
				GWT.log(error.getMessage()+"");
			}});
		}
	/* (non-Javadoc)
	 * @see com.neuresys.database.implstorage.gwtmobileimpl.StoreDataService#insertOrCreateDatabase(java.lang.String, com.neuresys.database.databaseimpl.jssqlite.SQLite)
	 */
	@Override
	public  void insertOrCreateDatabase(final String name,final SQLite c,final DatabaseSaveHandler savehandler)
	{
		Database db = Database.openDatabase(databaseName, databaseVersion, databaseDecription, 50000);
		db.transaction(new TransactionCallback(){

			@Override
			public void onTransactionStart(SQLTransaction transaction) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTransactionSuccess() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTransactionFailure(SQLError error) {
				// TODO Auto-generated method stub
				
			}});
		db.transaction(new TransactionCallback() {
		    public void onTransactionStart(SQLTransaction tx) {
		        tx.executeSql("CREATE TABLE IF NOT EXISTS MyDatabaseSQLite ("
		                + "id INT8 NOT NULL PRIMARY KEY AUTOINCREMENT,"
		                + "name VARCHAR, value BLOB)",null);
		      String toInsert=Base64Coder.encodeString(JsUtils.stringFromArrayBuffer(c.getDatabase().buffer()));
		      GWT.log(toInsert);
		      GWT.log("INSERT INTO MyDatabaseSQLite values("+name.hashCode()+","+name+",?)");
		        tx.executeSql("INSERT INTO MyDatabaseSQLite values(?,?,?)",new Object []{name.hashCode(),name,toInsert},
		        		new StatementCallback(){

							@Override
							public void onSuccess(SQLTransaction transaction,
									SQLResultSet resultSet) {
								savehandler.onSucceed(new DatabaseSaveEvent());
								
							}

							@Override
							public boolean onFailure(
									SQLTransaction transaction, SQLError error) {
								// TODO Auto-generated method stub
								return false;
							}
		        	
		        });
		    }
		    public void onTransactionFailure(SQLError error) {
		        // handle error...
		    }
		    public void onTransactionSuccess() {
		       
		    }
		});
	}
}
